package com.support.android.myapp3.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.razerdp.widget.animatedpieview.AnimatedPieView;
import com.razerdp.widget.animatedpieview.AnimatedPieViewConfig;
import com.razerdp.widget.animatedpieview.data.SimplePieInfo;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.support.android.myapp3.R;
import com.support.android.myapp3.domain.BXEnum;
import com.support.android.myapp3.util.Money;
import com.support.android.myapp3.util.TaxCalc;
import com.support.android.myapp3.util.Utils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;

public class Tax2Fragment extends Fragment {
    @BindView(R.id.edit_money)
    MaterialEditText moneyEdit;
    @BindView(R.id.btn_tax)
    Button taxBtn;
    //    @BindView(R.id.last_show)
//    LinearLayout lastShowLayout;
    @BindView(R.id.edit_sb)
    MaterialEditText editSb;
    @BindView(R.id.textlast_show1)
    MaterialEditText textLastShow1;
    @BindView(R.id.cardviewshow)
    LinearLayout showCardView;
    @BindView(R.id.taxListView)
    ListView taxListView;
    @BindView(R.id.taxanimatedPieView)
    AnimatedPieView animatedPieView;

    private Unbinder unbinder;
    private View view;
//    FragmentManager fm;
//    TextInputLayout moneyWrapper;

    private static Tax2Fragment fa;

    public static Tax2Fragment getInstance() {
        if (fa == null) {
            fa = new Tax2Fragment();
        }
        return fa;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_tax2, container, false);
        unbinder = ButterKnife.bind(this, view);
//        showCardView  = view.findViewById(R.id.cardviewshow);
//        fm = getChildFragmentManager();

        return view;
    }

    @OnTextChanged(R.id.edit_money)
    public void TextChanged() {

        if (textLastShow1.getVisibility() == View.GONE) {
            return;
        }

        textLastShow1.setVisibility(View.GONE);
        showCardView.setVisibility(View.GONE);

    }

    @OnClick(R.id.btn_tax)
    public void btnOnClick() {
        try {
            String moneyStr = moneyEdit.getText().toString();

            //判断有无输入
            if (TextUtils.isEmpty(moneyStr) || validateNum(moneyStr) == false) {
                ;
                moneyEdit.setError("请输入有效数据");
                Toast.makeText(getActivity(), "没有数据输入", Toast.LENGTH_LONG).show();
                return;
            }

            String lastYuan = showCardView(moneyStr);

            textLastShow1.setText(lastYuan);

            if (textLastShow1.getVisibility() == View.GONE) {
                textLastShow1.setVisibility(View.VISIBLE);
                showCardView.setVisibility(View.VISIBLE);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            Toast.makeText(getActivity(), "系统处理异常", Toast.LENGTH_LONG).show();
        }
    }


    public String showCardView(String moneyYuan) {
       TaxCalc tax = new TaxCalc(moneyYuan);

        List<Map<String, String>> data = calcListData(tax);

        SimpleAdapter adapter = new SimpleAdapter(getActivity(), data, R.layout.item_tax_list,
                new String[]{"p_name", "p_person","p_company"}, new int[]{R.id.p_name, R.id.p_person,R.id.p_company});

        taxListView.setAdapter(adapter);

        AnimatedPieView mAnimatedPieView = view.findViewById(R.id.taxanimatedPieView);

        float lastF = calcPer(tax.getLastCMoney(),tax.getMoney());
        float yanglaoF = calcPer(tax.getTaxMap().get(BXEnum.YANG_LAO.getName()).calcPersonTax(),tax.getMoney());
        float yiliaoF =  calcPer(tax.getTaxMap().get(BXEnum.YI_LIAO.getName()).calcPersonTax(),tax.getMoney());
        float shiyeF = calcPer(tax.getTaxMap().get(BXEnum.SHI_YE.getName()).calcPersonTax(),tax.getMoney());
        float zhufangF =  calcPer(tax.getTaxMap().get(BXEnum.ZHU_FANG.getName()).calcPersonTax(),tax.getMoney());
        float persongF =  calcPer(tax.getPersonTax().calcTax(),tax.getMoney());

        AnimatedPieViewConfig config = new AnimatedPieViewConfig();
        config.startAngle(-90)// 起始角度偏移
                .addData(new SimplePieInfo(lastF, Utils.getColor("FFADCBD6"), perShow("税后月薪",tax.getLastPMoney(),tax.getMoney())))//数据（实现IPieInfo接口的bean）
                .addData(new SimplePieInfo(yanglaoF, Utils.getColor("FFDEDFDE"), perShow(tax.getTaxMap().get(BXEnum.YANG_LAO.getName()).getName(),tax.getTaxMap().get(BXEnum.YANG_LAO.getName()).calcPersonTax(),tax.getMoney())))
                .addData(new SimplePieInfo(yiliaoF, Utils.getColor("FFFF3C39"), perShow(tax.getTaxMap().get(BXEnum.YI_LIAO.getName()).getName(),tax.getTaxMap().get(BXEnum.YI_LIAO.getName()).calcPersonTax(),tax.getMoney())))
                .addData(new SimplePieInfo(shiyeF, Utils.getColor("FF42C3BD"),perShow(tax.getTaxMap().get(BXEnum.SHI_YE.getName()).getName(),tax.getTaxMap().get(BXEnum.SHI_YE.getName()).calcPersonTax(),tax.getMoney())))
                .addData(new SimplePieInfo(zhufangF, Utils.getColor("FFFFB65A"), perShow(tax.getTaxMap().get(BXEnum.ZHU_FANG.getName()).getName(),tax.getTaxMap().get(BXEnum.ZHU_FANG.getName()).calcPersonTax(),tax.getMoney())))
                .addData(new SimplePieInfo(persongF, Utils.getColor("FF949EB5"), perShow(tax.getPersonTax().getName(),tax.getPersonTax().calcTax(),tax.getMoney())))
                .drawText(true)
                .textSize(20)
                .duration(2000);// 持续时间

        mAnimatedPieView.start(config);

        setListViewHeightBasedOnChildren(taxListView);

        return tax.getLastPMoney().getYuan();
    }


    public List<Map<String, String>> calcListData( TaxCalc taxCalc) {


        List<Map<String, String>> data = new ArrayList<>();
        data.add(genItem("五险一金汇缴明细", " ", " "));
        data.add(genItem("               ", "个人缴纳部分", "单位缴纳部分"));

        for (Map.Entry<String, TaxCalc.PublicTaxCalc> entry : taxCalc.getTaxMap().entrySet()) {
            data.add(genItem(entry.getValue()));
        }

        data.add(genItem("共计支出", taxCalc.getBaoxianPersonMoney().getYuan_Round_UP(), taxCalc.getBaoxianCompanyMoney().getYuan_Round_UP()));

        data.add(genItem("个人所得税汇缴明细", " ", " "));
        data.add(genItem("扣除王五险一金后月薪(应税工资)", " ", taxCalc.getAfterBaoxianMoney().getYuan_Round_UP()));
        data.add(genItem("个人所得税", " ", taxCalc.getPersonTax().calcTax().getYuan()));
        data.add(genItem("税后工资", " ", taxCalc.getLastPMoney().getYuan_Round_UP()));
        data.add(genItem("公司支出", " ", taxCalc.getLastCMoney().getYuan_Round_UP()));
        return data;
    }


    public Map<String, String> genItem(String col1, String col2, String col3) {
        HashMap<String, String> item = new HashMap<String, String>();
        item.put("p_name", col1);
        item.put("p_person", col2);
        item.put("p_company", col3);
        return item;
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 30 ;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    public String perShow(String item,Money money,Money allMoney){
        return String.format("%s:比例%s%%:%s ",item, money.divideMoney(allMoney).multiplyNum("100").getYuan_Round_UP(),money.getYuan() );
    }

    public String moneyShow(Money money,String per){
        return money.getYuan_Round_UP()+String.format("(%s%%)",per);
    }

    public Map<String,String> genItem(TaxCalc.PublicTaxCalc taxCalc){
        HashMap<String, String> item = new HashMap<String, String>();
        item.put("p_name",taxCalc.getName());
        item.put("p_person",moneyShow(taxCalc.calcPersonTax(),taxCalc.getPersonPer()));
        item.put("p_company",moneyShow(taxCalc.calcCompanygTax(),taxCalc.getCompanyPer()));
        return item;
    }

    public float calcPer(Money money1,Money money2){
        return Float.parseFloat(money1.divideMoney(money2).multiplyNum("100").getYuan());
    }

    public boolean validateNum(String num) {
        try {
            new BigDecimal(num);
        } catch (Exception ex) {
            return false;
        }

        return true;
    }

    /**
     * onDestroyView中进行解绑操作
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

}
